﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Fall.Core.Attributes;
using Fall.Core.BaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fall.Core.Filters
{
    public class CommonResultServiceFilter : ActionFilterAttribute
    {
        /// <summary>
        /// Action执行完成,返回结果处理
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            // 重新封装回传格式
            if (actionExecutedContext.Exception == null)
            {
                var controllerActionDescriptor = actionExecutedContext.ActionDescriptor as ControllerActionDescriptor;
                var dotWrapAction = controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(DontWrapRusultAttribute), false).FirstOrDefault();
                var dotWrapController = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(typeof(DontWrapRusultAttribute), false).FirstOrDefault();
                if (actionExecutedContext.Result is ObjectResult result && dotWrapAction == null && dotWrapController == null)
                {   
                    ObjectResult objectResult = new(CommonResult<object>.Success(actionExecutedContext.HttpContext.Response.StatusCode.ToString(), result.Value));
                    actionExecutedContext.Result = objectResult;
                }
            }
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}
